<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }
    public function loginhome(){
        return $this->fetch();
    }
    public function register(){
        return $this->fetch();
    }
    public function register_step2(Request $request){
        $data=$request->param();
        foreach ($data as $v){
            if($v ==''){
                return $this->error('用户名或者密码不能为空');
            }
        }
        if($data['password'] != $data['password2']){
            return $this->error('两次输入的密码不一致');
        }
        $where['username']=$data['username'];
        $find=Db::name('admin_user')->where($where)->find();
        if($find){
            return $this->error('用户名已经注册');
        }
        $data['password']=md5($data['password']);
        unset($data['password2']);
        $save=Db::name('user')
            ->insert($data);
        if($save) {
            Session::set('username',$data['username']);
            return $this->success('注册成功', url('index/index/inf'));
        }
    }
    public function inf(){
        if(!Session::has('username')){
            return $this->redirect(url('index'));
        }
        //跳转到雨情总站
        return $this->redirect('http://www.lightrain.org.cn');
        $username=Session::get('username');
        $this->assign('username',$username);
        return $this->fetch();
        dump();
    }

    //登录后台
    public function login($username='',$password=''){
        if($username=='' || $password==''){
            $this->error('用户名或者密码不能为空！');
        }
        $res=Db::name('user')
            ->where(['username'=>$username])
            ->find();
        if($res['password']==md5($password)){
            Session::set('username',$res['username']);
            $this->success('登录成功！',url('index/index/inf'));
        }else{
            $this->error('登录失败！');
        }
    }

    //退出登录
    public function loginout(){
        if(!Session::has('username')){
            $this->success('你尚未登录！',url('index/index/index'));
        }
        Session::delete('username');
        $this->success('成功退出！',url('index/index/index'));
    }
}
